package nio;

import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * 管道
 */
public class PipeTest {

    @Test
    public void test() throws Exception {
        // 1. 获取管道
        Pipe pipe = Pipe.open();

        // 2.　将缓冲区中的数据写入通道
        ByteBuffer buf = ByteBuffer.allocate(1024);

        Pipe.SinkChannel sinkChannel = pipe.sink();
        buf.put("测试通过管道发送数据".getBytes());
        buf.flip();
        sinkChannel.write(buf);
        buf.clear();

        // 3. 读取缓冲区中的数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        int len = sourceChannel.read(buf);
        buf.flip();
        System.out.println(new String(buf.array(), 0, len));

        sourceChannel.close();
        sinkChannel.close();
    }

}
